import 'package:flutter/material.dart';
import 'package:photo_manager/photo_manager.dart';
import 'dart:typed_data';
import 'dart:async'; // 添加异步支持
import 'dart:io'; // 添加dart:io包
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:path_provider/path_provider.dart';

// 添加导入
import 'package:device_info_plus/device_info_plus.dart';

// 添加状态提供者导入
import '../riverpod/photo_backup_notifier.dart';

// 添加UploadTasksScreen导入
import '../screens/upload_tasks_screen.dart';

// 添加Routes导入
import '../routes.dart';

class PhotoBackupPage extends ConsumerStatefulWidget {
  const PhotoBackupPage({Key? key}) : super(key: key);

  @override
  ConsumerState<PhotoBackupPage> createState() => _PhotoBackupPageState();
}

class _PhotoBackupPageState extends ConsumerState<PhotoBackupPage>
    with TickerProviderStateMixin {
  // 动画控制器
  late AnimationController _animationController;
  late AnimationController _tipSwitchController;

  // 刷新按钮动画控制器
  late AnimationController _refreshController;

  // 动画时长
  final Duration _animationDuration = const Duration(milliseconds: 300);
  final Duration _tipSwitchDuration = const Duration(milliseconds: 500);
  final Duration _refreshDuration = const Duration(milliseconds: 1500);

  // 加载状态变量
  bool _isLoading = true;
  bool _isError = false;
  String _errorMessage = '';
  double _loadingProgress = 0.0;

  // 设备型号
  String _deviceModel = '';

  // 滚动控制器
  final ScrollController _scrollController = ScrollController();

  // 是否已加载数据
  bool _hasLoadedData = false;

  // 是否正在加载批次
  bool _isLoadingBatch = false;

  // 待加载的相册
  List<AssetPathEntity> _pendingAlbums = [];

  // 批次大小
  final int _batchSize = 3;

  // 批次加载定时器
  Timer? _batchLoadingTimer;

  // 相册缓存
  List<AssetPathEntity> _albums = [];
  List<AssetPathEntity> _allAlbumCache = [];
  Map<String, Map<AssetType, int>> _albumAssetCountCache = {};

  // 缩略图缓存
  Map<String, Uint8List?> _thumbnailCache = {};

  // 是否正在刷新
  bool _isRefreshing = false;

  // 防抖计时器
  Timer? _debounceTimer;

  @override
  void initState() {
    super.initState();

    // 初始化动画控制器
    _animationController = AnimationController(
      vsync: this,
      duration: _animationDuration,
    );

    _tipSwitchController = AnimationController(
      vsync: this,
      duration: _tipSwitchDuration,
    );

    // 初始化刷新动画控制器
    _refreshController = AnimationController(
      vsync: this,
      duration: _refreshDuration,
    );

    // 获取设备信息
    _getDeviceInfo();

    // 加载相册
    _loadAlbums();
  }

  @override
  void dispose() {
    _scrollController.removeListener(_onScroll);
    _scrollController.dispose();
    _batchLoadingTimer?.cancel();
    _debounceTimer?.cancel();
    _animationController.dispose();
    _tipSwitchController.dispose();
    _refreshController.dispose();
    // 确保所有异步操作都被取消
    _pendingAlbums.clear();
    super.dispose();
  }

  // 监听滚动，当接近底部时自动加载更多
  void _onScroll() {
    if (_scrollController.position.pixels >
            _scrollController.position.maxScrollExtent - 200 &&
        !_isLoadingBatch &&
        _pendingAlbums.isNotEmpty) {
      _loadNextBatch();
    }
  }

  // 请求权限并加载相册
  Future<void> _requestPermissionAndLoadAlbums() async {
    // 请求权限
    final PermissionState result = await PhotoManager.requestPermissionExtend();
    if (result.isAuth) {
      // 加载相册
      await _loadAlbums();
    } else {
      // 显示权限提示
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('需要相册权限才能获取相册列表'),
            duration: Duration(seconds: 2),
          ),
        );
      }
    }
  }

  // 修改后的加载相册列表 - 只获取相册列表，不立即加载详情
  Future<void> _loadAlbums() async {
    setState(() => _isLoading = true);

    // 显示加载提示
    _tipSwitchController.forward();

    // 如果已加载数据则从缓存过滤显示
    if (_hasLoadedData && _allAlbumCache.isNotEmpty) {
      _filterAlbumsFromCache();
      return;
    }

    try {
      final PermissionState ps = await PhotoManager.requestPermissionExtend();
      if (!ps.isAuth) {
        throw Exception('未授权访问相册');
      }

      // 读取全局缓存状态
      final backupState = ref.read(photoBackupProvider);

      // 检查全局状态中是否有缓存的相册信息
      if (backupState.albumCache.isNotEmpty) {
        _hasLoadedData = true;

        // 使用缓存数据初始化相册列表
        await _loadFromGlobalCache();

        // 显示已缓存的相册
        _filterAlbumsFromCache();

        // 在后台更新相册列表以保持数据最新
        _updateAlbumsInBackground();
        return;
      }

      // 获取所有相册（包括照片和视频）
      final List<AssetPathEntity> allAlbums =
          await PhotoManager.getAssetPathList(
            hasAll: true,
            onlyAll: false,
            type:
                backupState.autoBackupPhotos
                    ? (backupState.autoBackupVideos
                        ? RequestType.common
                        : RequestType.image)
                    : RequestType.video,
          );

      // 筛选相册 - 过滤掉Recent相册
      final List<AssetPathEntity> filteredAlbums = [];
      for (var album in allAlbums) {
        final String albumName = album.name.toLowerCase();
        // 跳过Recent相册（包括英文和中文）
        if (albumName.contains('recent') || albumName.contains('最近')) {
          continue;
        }

        // 获取相册总资源数
        final int totalCount = await album.assetCountAsync;
        if (totalCount > 0) {
          filteredAlbums.add(album);
          // 初始化选择状态，使用全局状态提供者
          ref
              .read(photoBackupProvider.notifier)
              .initAlbumSelection(album.id, true);
        }
      }

      // 保存所有相册到缓存
      _allAlbumCache = filteredAlbums;

      // 设置待加载队列
      _pendingAlbums = List.from(filteredAlbums);
      _hasLoadedData = true;

      // 开始加载第一批
      setState(() => _isLoading = false);

      // 开始自动加载批次
      _loadNextBatch();
    } catch (e) {
      if (mounted) {
        setState(() {
          _isLoading = false;
          _isError = true;
          _errorMessage = e.toString();
        });

        // 出错时恢复显示加密备份提示
        _tipSwitchController.reverse();
      }
    }
  }

  // 从全局缓存加载相册信息
  Future<void> _loadFromGlobalCache() async {
    try {
      final backupState = ref.read(photoBackupProvider);
      final List<AssetPathEntity> albumList = [];

      // 获取最新的相册列表作为基础
      final List<AssetPathEntity> allAlbums =
          await PhotoManager.getAssetPathList(
            hasAll: true,
            onlyAll: false,
            type:
                backupState.autoBackupPhotos
                    ? (backupState.autoBackupVideos
                        ? RequestType.common
                        : RequestType.image)
                    : RequestType.video,
          );

      // 筛选掉Recent相册
      final List<AssetPathEntity> filteredAlbums = [];
      for (var album in allAlbums) {
        final String albumName = album.name.toLowerCase();
        if (albumName.contains('recent') || albumName.contains('最近')) {
          continue;
        }
        filteredAlbums.add(album);
      }

      // 使用Map加速查找
      final Map<String, AssetPathEntity> albumMap = {
        for (var album in filteredAlbums) album.id: album,
      };

      // 使用缓存的相册信息填充数据
      for (var cachedAlbum in backupState.albumCache) {
        // 如果相册仍然存在
        if (albumMap.containsKey(cachedAlbum.id)) {
          final album = albumMap[cachedAlbum.id]!;

          // 只添加具有内容的相册
          if (cachedAlbum.imageCount > 0 || cachedAlbum.videoCount > 0) {
            albumList.add(album);

            // 使用缓存的统计数据
            _albumAssetCountCache[album.id] = {
              AssetType.image: cachedAlbum.imageCount,
              AssetType.video: cachedAlbum.videoCount,
            };

            // 加载缓存的缩略图
            if (cachedAlbum.thumbnailPath != null) {
              try {
                final file = File(cachedAlbum.thumbnailPath!);
                if (await file.exists()) {
                  final bytes = await file.readAsBytes();
                  if (mounted) {
                    setState(() {
                      _thumbnailCache[album.id] = bytes;
                    });
                  }
                }
              } catch (e) {
                print('加载缓存缩略图失败: $e');
              }
            }
          }
        }
      }

      // 更新相册缓存
      if (mounted) {
        setState(() {
          _allAlbumCache = albumList;
          // 关闭进度提示，因为数据已从缓存加载完成
          _isLoading = false;
        });

        // 切换到备份提示
        _tipSwitchController.reverse();
      }
    } catch (e) {
      print('从全局缓存加载相册失败: $e');
    }
  }

  // 在后台更新相册列表以保持数据最新
  void _updateAlbumsInBackground() async {
    try {
      final backupState = ref.read(photoBackupProvider);

      // 获取最新的相册列表
      final List<AssetPathEntity> allAlbums =
          await PhotoManager.getAssetPathList(
            hasAll: true,
            onlyAll: false,
            type:
                backupState.autoBackupPhotos
                    ? (backupState.autoBackupVideos
                        ? RequestType.common
                        : RequestType.image)
                    : RequestType.video,
          );

      // 筛选掉Recent相册
      final List<AssetPathEntity> filteredAlbums = [];
      for (var album in allAlbums) {
        final String albumName = album.name.toLowerCase();
        if (albumName.contains('recent') || albumName.contains('最近')) {
          continue;
        }

        // 获取相册总资源数
        final int totalCount = await album.assetCountAsync;
        if (totalCount > 0) {
          filteredAlbums.add(album);
        }
      }

      if (!mounted) return;

      // 更新相册缓存
      _allAlbumCache = filteredAlbums;
      _pendingAlbums = List.from(filteredAlbums);

      // 标记哪些相册需要更新
      final Set<String> existingAlbumIds = Set.from(_albumAssetCountCache.keys);
      _pendingAlbums =
          _pendingAlbums
              .where((album) => !existingAlbumIds.contains(album.id))
              .toList();

      // 如果有新相册，启动批量加载
      if (_pendingAlbums.isNotEmpty) {
        _isLoadingBatch = false;
        _loadNextBatch();
      }
    } catch (e) {
      print('后台更新相册失败: $e');
    }
  }

  // 分批加载相册详情并缓存到全局状态
  Future<void> _loadNextBatch() async {
    if (!mounted || _isLoadingBatch || _pendingAlbums.isEmpty) return;

    setState(() => _isLoadingBatch = true);

    try {
      // 获取批次大小
      final int count =
          _pendingAlbums.length > _batchSize
              ? _batchSize
              : _pendingAlbums.length;

      // 提取当前批次的相册
      final List<AssetPathEntity> currentBatch = _pendingAlbums.sublist(
        0,
        count,
      );

      // 为每个相册加载详细数据
      for (var album in currentBatch) {
        if (!mounted) return; // 添加mounted检查
        await _loadAlbumDetails(album);

        if (!mounted) return; // 添加mounted检查
        setState(() {
          // 将已加载的相册从待加载队列中移除
          _pendingAlbums.remove(album);
          // 过滤并显示已加载的相册
          _filterAlbumsFromCache();
        });
      }

      if (!mounted) return; // 添加mounted检查
      setState(() => _isLoadingBatch = false);

      // 如果还有待加载相册，则安排加载下一批
      if (_pendingAlbums.isNotEmpty && mounted) {
        // 使用定时器延迟加载下一批，给UI一些喘息的机会
        _batchLoadingTimer?.cancel();
        _batchLoadingTimer = Timer(const Duration(milliseconds: 500), () {
          if (mounted && _pendingAlbums.isNotEmpty) {
            _loadNextBatch();
          }
        });
      } else if (mounted) {
        // 所有相册都加载完成后恢复显示加密备份提示
        _tipSwitchController.reverse();

        // 所有相册加载完成后，更新全局状态缓存
        await _updateGlobalStateCache();
      }
    } catch (e) {
      print('加载批次失败: $e');
      if (!mounted) return;
      setState(() => _isLoadingBatch = false);

      // 如果没有更多相册要加载，则恢复显示加密备份提示
      if (_pendingAlbums.isEmpty && mounted) {
        _tipSwitchController.reverse();
      }
    }
  }

  // 更新全局状态缓存
  Future<void> _updateGlobalStateCache() async {
    if (!mounted) return;

    try {
      final photoBackupNotifier = ref.read(photoBackupProvider.notifier);
      final List<AlbumInfo> albumInfoList = [];

      // 创建AlbumInfo对象列表
      for (var album in _allAlbumCache) {
        final typeCount = _albumAssetCountCache[album.id];
        final thumbnailBytes = _thumbnailCache[album.id];

        if (typeCount != null) {
          // 等待获取缩略图保存路径
          String? thumbnailPath;
          if (thumbnailBytes != null) {
            try {
              thumbnailPath = await photoBackupNotifier.saveThumbnailToFile(
                album.id,
                thumbnailBytes,
              );
            } catch (e) {
              print('保存缩略图失败: $e');
            }
          }

          // 创建相册信息
          final albumInfo = AlbumInfo(
            id: album.id,
            name: album.name,
            imageCount: typeCount[AssetType.image] ?? 0,
            videoCount: typeCount[AssetType.video] ?? 0,
            thumbnailPath: thumbnailPath,
          );

          albumInfoList.add(albumInfo);
        }
      }

      // 更新全局状态
      photoBackupNotifier.setAlbumCache(albumInfoList);

      // 初始化选择状态
      photoBackupNotifier.initAlbumsSelectionFromInfo(albumInfoList);

      // 持久化保存状态
      await photoBackupNotifier.saveState();
    } catch (e) {
      print('更新全局状态缓存失败: $e');
    }
  }

  // 加载单个相册的所有详细信息
  Future<void> _loadAlbumDetails(AssetPathEntity album) async {
    // 精确计算照片和视频数量
    await _cacheAlbumAssetCount(album);
    // 加载缩略图
    await _loadThumbnail(album);
  }

  // 缓存相册的资源类型数量 - 确保精确计数
  Future<void> _cacheAlbumAssetCount(AssetPathEntity album) async {
    try {
      // 获取相册总资源数
      final int totalCount = await album.assetCountAsync;
      if (totalCount == 0) {
        if (mounted) {
          setState(() {
            _albumAssetCountCache[album.id] = {
              AssetType.image: 0,
              AssetType.video: 0,
            };
          });
        }
        return;
      }

      // 获取所有资源 - 这里获取所有资源以确保精确统计
      final List<AssetEntity> assets = await album.getAssetListRange(
        start: 0,
        end: totalCount,
      );

      // 统计各类型数量
      int imageCount = 0;
      int videoCount = 0;

      for (var asset in assets) {
        if (asset.type == AssetType.image) {
          imageCount++;
        } else if (asset.type == AssetType.video) {
          videoCount++;
        }
      }

      // 缓存结果
      if (mounted) {
        setState(() {
          _albumAssetCountCache[album.id] = {
            AssetType.image: imageCount,
            AssetType.video: videoCount,
          };
        });
      }
    } catch (e) {
      print('缓存相册资源数量失败: $e');
    }
  }

  // 从缓存过滤要显示的相册
  void _filterAlbumsFromCache() {
    if (_allAlbumCache.isEmpty) {
      setState(() {
        _albums = [];
        _isLoading = false;
      });
      return;
    }

    List<AssetPathEntity> filteredAlbums = [];
    final Map<String, int> countMap = {};

    // 获取全局备份状态
    final backupState = ref.read(photoBackupProvider);

    // 根据当前开关状态过滤相册和计算数量
    for (var album in _allAlbumCache) {
      final typeCount = _albumAssetCountCache[album.id];
      if (typeCount != null) {
        int relevantCount = 0;

        if (backupState.autoBackupPhotos && backupState.autoBackupVideos) {
          // 照片和视频
          relevantCount =
              (typeCount[AssetType.image] ?? 0) +
              (typeCount[AssetType.video] ?? 0);
        } else if (backupState.autoBackupPhotos) {
          // 只有照片
          relevantCount = typeCount[AssetType.image] ?? 0;
        } else if (backupState.autoBackupVideos) {
          // 只有视频
          relevantCount = typeCount[AssetType.video] ?? 0;
        }

        if (relevantCount > 0) {
          filteredAlbums.add(album);
          countMap[album.id] = relevantCount;
        }
      }
    }

    // 按相关资源数量从多到少排序
    filteredAlbums.sort(
      (a, b) => (countMap[b.id] ?? 0).compareTo(countMap[a.id] ?? 0),
    );

    setState(() {
      _albums = filteredAlbums;
      _isLoading = false;

      // 更新动画状态
      if (backupState.autoBackupPhotos || backupState.autoBackupVideos) {
        _animationController.forward();
      } else {
        _animationController.reverse();
      }
    });
  }

  // 检查是否存在缓存的缩略图（辅助函数，不改变现有UI）
  Future<Uint8List?> _checkCachedThumbnail(String albumId) async {
    try {
      // 从全局状态获取相册信息
      final state = ref.read(photoBackupProvider);
      final cachedAlbum = state.albumCache.firstWhere(
        (album) => album.id == albumId,
        orElse: () => const AlbumInfo(id: '', name: ''),
      );

      // 如果有缓存的缩略图路径，并且文件存在，则加载
      if (cachedAlbum.thumbnailPath != null) {
        final file = File(cachedAlbum.thumbnailPath!);
        if (await file.exists()) {
          final bytes = await file.readAsBytes();
          return bytes;
        }
      }
    } catch (e) {
      print('检查缓存缩略图失败: $e');
    }
    return null;
  }

  // 加载相册缩略图
  Future<void> _loadThumbnail(AssetPathEntity album) async {
    // 先检查是否有缓存的缩略图
    final cachedThumbnail = await _checkCachedThumbnail(album.id);
    if (cachedThumbnail != null && mounted) {
      setState(() {
        _thumbnailCache[album.id] = cachedThumbnail;
      });
      return;
    }

    try {
      // 没有缓存，则从相册中获取第一个资源作为缩略图
      final List<AssetEntity> assets = await album.getAssetListRange(
        start: 0,
        end: 1,
      );
      if (assets.isNotEmpty) {
        final Uint8List? thumbnail = await assets.first.thumbnailDataWithSize(
          const ThumbnailSize(120, 120),
          quality: 80,
        );

        if (mounted && thumbnail != null) {
          // 保存缩略图到内存缓存
          setState(() {
            _thumbnailCache[album.id] = thumbnail;
          });

          // 保存缩略图到本地文件系统
          if (thumbnail.isNotEmpty) {
            _saveThumbnailToFile(album.id, thumbnail);
          }
        }
      }
    } catch (e) {
      print('加载缩略图失败: $e');
    }
  }

  // 保存缩略图到本地文件系统
  Future<String?> _saveThumbnailToFile(
    String albumId,
    Uint8List thumbnailData,
  ) async {
    try {
      final photoBackupNotifier = ref.read(photoBackupProvider.notifier);
      return await photoBackupNotifier.saveThumbnailToFile(
        albumId,
        thumbnailData,
      );
    } catch (e) {
      print('保存缩略图到文件系统失败: $e');
      return null;
    }
  }

  // 添加获取设备信息的方法
  Future<void> _getDeviceInfo() async {
    try {
      DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
      // 使用dart:io包判断平台，而不是Theme.of(context)
      if (Platform.isAndroid) {
        AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
        setState(() {
          _deviceModel = androidInfo.model;
        });
        // 添加成功获取Android设备信息的调试日志
        print('成功获取到Android设备信息: ${androidInfo.model}');
      } else if (Platform.isIOS) {
        IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
        setState(() {
          _deviceModel = iosInfo.utsname.machine;
        });
        // 添加成功获取iOS设备信息的调试日志
        print('成功获取到iOS设备信息: ${iosInfo.utsname.machine}');
      }
    } catch (e) {
      // 出错时保持默认值
      print('获取设备信息失败: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;
    // 使用 Riverpod 消费全局状态
    final backupState = ref.watch(photoBackupProvider);

    return Scaffold(
      // 修改背景色为略微偏灰的颜色，与卡片形成对比
      backgroundColor:
          theme.brightness == Brightness.light
              ? colorScheme.surface.withOpacity(0.95)
              : colorScheme.surface.withOpacity(0.2),
      appBar: AppBar(
        title: const Text('相册备份'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.of(context).pop(),
        ),
        elevation: 0,
        backgroundColor: colorScheme.surface,
        foregroundColor: colorScheme.onSurface,
      ),
      body: Column(
        children: [
          // 顶部提示条动画包装
          AnimatedBuilder(
            animation: _tipSwitchController,
            builder: (context, child) {
              return SizeTransition(
                sizeFactor: _animationController,
                axisAlignment: -1.0,
                child: FadeTransition(
                  opacity: _animationController,
                  child: Container(
                    width: double.infinity,
                    padding: const EdgeInsets.symmetric(
                      horizontal: 16,
                      vertical: 3,
                    ),
                    color: colorScheme.primary.withOpacity(0.08),
                    child:
                        _tipSwitchController.value > 0.5
                            ? _buildLoadingTip(colorScheme)
                            : _buildEncryptionTip(colorScheme),
                  ),
                ),
              );
            },
          ),

          Expanded(
            child: Column(
              children: [
                Expanded(
                  child: SingleChildScrollView(
                    controller: _scrollController,
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 12.0),
                      child: Column(
                        children: [
                          // 自动备份照片
                          _buildCardItem(
                            child: _buildMainSwitchTile(
                              title: '自动备份照片',
                              labelText: '原图',
                              value: backupState.autoBackupPhotos,
                              onChanged: (value) {
                                ref
                                    .read(photoBackupProvider.notifier)
                                    .setAutoBackupPhotos(value);
                                // 从缓存中过滤显示相册
                                _filterAlbumsFromCache();
                              },
                            ),
                          ),

                          const SizedBox(height: 4),

                          // 自动备份视频、原图备份和压缩备份组合卡片
                          _buildCardItem(
                            child: Column(
                              children: [
                                // 自动备份视频
                                _buildMainSwitchTile(
                                  title: '自动备份视频',
                                  value: backupState.autoBackupVideos,
                                  onChanged: (value) {
                                    ref
                                        .read(photoBackupProvider.notifier)
                                        .setAutoBackupVideos(value);
                                    // 从缓存中过滤显示相册
                                    _filterAlbumsFromCache();
                                  },
                                ),

                                // 当自动备份视频开启时才显示以下选项 - 使用动画
                                AnimatedSize(
                                  duration: _animationDuration,
                                  curve: Curves.easeInOut,
                                  child:
                                      backupState.autoBackupVideos
                                          ? Column(
                                            children: [
                                              const Divider(
                                                height: 1,
                                                thickness: 0.5,
                                              ),
                                              // 原图备份选项
                                              _buildVipSwitchTile(
                                                title: '原图备份',
                                                subtitle: '保留视频原始画质（推荐）',
                                                value:
                                                    backupState.originalBackup,
                                                onChanged: (value) {
                                                  ref
                                                      .read(
                                                        photoBackupProvider
                                                            .notifier,
                                                      )
                                                      .setOriginalBackup(value);
                                                },
                                              ),
                                              const Divider(
                                                height: 1,
                                                thickness: 0.5,
                                              ),
                                              // 压缩备份选项
                                              _buildSelectionTile(
                                                title: '压缩备份',
                                                subtitle: '有损图片，视频压缩后上传',
                                                selected:
                                                    backupState
                                                        .compressedBackup,
                                                onTap: () {
                                                  ref
                                                      .read(
                                                        photoBackupProvider
                                                            .notifier,
                                                      )
                                                      .setCompressedBackup(
                                                        true,
                                                      );
                                                },
                                              ),
                                            ],
                                          )
                                          : Container(),
                                ),
                              ],
                            ),
                          ),

                          const SizedBox(height: 4),

                          // 并行备份数量和流量备份设置组合卡片
                          _buildCardItem(
                            child: Column(
                              children: [
                                // 并行备份数量
                                _buildNavigationTile(
                                  title: '并行备份数量',
                                  label: '${backupState.parallelBackupCount}',
                                  labelColor: Colors.red,
                                  onTap: () {
                                    _showParallelBackupCountDialog();
                                  },
                                ),

                                // 仅当自动备份照片开启时显示
                                if (backupState.autoBackupPhotos) ...[
                                  const Divider(height: 1, thickness: 0.5),

                                  // 使用手机流量备份照片
                                  _buildMainSwitchTile(
                                    title: '使用手机流量备份照片',
                                    value: backupState.useMobileDataForPhotos,
                                    onChanged: (value) {
                                      ref
                                          .read(photoBackupProvider.notifier)
                                          .setUseMobileDataForPhotos(value);
                                    },
                                  ),
                                ],

                                // 仅当自动备份视频开启时显示
                                if (backupState.autoBackupVideos) ...[
                                  if (backupState.autoBackupPhotos)
                                    const Divider(height: 1, thickness: 0.5)
                                  else if (!_albums.isEmpty) // 确保只在有必要时添加分隔线
                                    const Divider(height: 1, thickness: 0.5),

                                  // 使用手机流量备份视频
                                  _buildMainSwitchTile(
                                    title: '使用手机流量备份视频',
                                    value: backupState.useMobileDataForVideos,
                                    onChanged: (value) {
                                      ref
                                          .read(photoBackupProvider.notifier)
                                          .setUseMobileDataForVideos(value);
                                    },
                                  ),
                                ],
                              ],
                            ),
                          ),

                          // 备份信息 - 修改文本格式
                          Container(
                            width: double.infinity,
                            padding: const EdgeInsets.all(12.0),
                            margin: const EdgeInsets.symmetric(vertical: 4),
                            child: Text(
                              '照片及视频备份至文件夹：$_deviceModel',
                              style: const TextStyle(
                                fontSize: 12,
                                color: Colors.grey,
                              ),
                            ),
                          ),

                          // 相册选择标题 - 使用动画
                          _buildAlbumSelectionTitle(),

                          // 相册列表 - 使用动画
                          FadeTransition(
                            opacity: _animationController,
                            child: SizeTransition(
                              sizeFactor: _animationController,
                              axisAlignment: -1.0,
                              child: Column(
                                children: [
                                  if (_isLoading)
                                    const Center(
                                      child: Padding(
                                        padding: EdgeInsets.all(20.0),
                                        child: Column(
                                          children: [
                                            CircularProgressIndicator(),
                                            SizedBox(height: 10),
                                            Text(
                                              '加载相册中...',
                                              style: TextStyle(
                                                fontSize: 14,
                                                color: Colors.grey,
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    )
                                  else if (_albums.isEmpty &&
                                      _pendingAlbums.isEmpty)
                                    _buildCardItem(
                                      child: const Padding(
                                        padding: EdgeInsets.all(16.0),
                                        child: Center(
                                          child: Text(
                                            '没有找到相册',
                                            style: TextStyle(
                                              fontSize: 14,
                                              color: Colors.grey,
                                            ),
                                          ),
                                        ),
                                      ),
                                    )
                                  else
                                    ..._buildRealAlbumsList(),
                                ],
                              ),
                            ),
                          ),

                          // 添加底部留白
                          const SizedBox(height: 20),

                          // 底部信息 - 当有相册且自动备份开启时在滚动区域内显示
                          if ((_albums.isNotEmpty ||
                                  _pendingAlbums.isNotEmpty) &&
                              (backupState.autoBackupPhotos ||
                                  backupState.autoBackupVideos))
                            Padding(
                              padding: const EdgeInsets.only(bottom: 40.0),
                              child: Center(
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    const Icon(
                                      Icons.info_outline,
                                      color: Colors.grey,
                                      size: 16,
                                    ),
                                    const SizedBox(width: 8),
                                    const Text(
                                      '咕噜酱默认使用喵语加密存储',
                                      style: TextStyle(
                                        fontSize: 12,
                                        color: Colors.grey,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                        ],
                      ),
                    ),
                  ),
                ),

                // 底部信息 - 仅当相册为空或自动备份关闭时在底部固定位置显示
                if ((_albums.isEmpty && _pendingAlbums.isEmpty) ||
                    (!backupState.autoBackupPhotos &&
                        !backupState.autoBackupVideos))
                  Padding(
                    padding: const EdgeInsets.symmetric(vertical: 20.0),
                    child: Center(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          const Icon(
                            Icons.info_outline,
                            color: Colors.grey,
                            size: 16,
                          ),
                          const SizedBox(width: 8),
                          const Text(
                            '咕噜酱默认使用喵语加密存储',
                            style: TextStyle(fontSize: 12, color: Colors.grey),
                          ),
                        ],
                      ),
                    ),
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCardItem({required Widget child}) {
    final theme = Theme.of(context);
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 2.0),
      decoration: BoxDecoration(
        color: theme.cardColor,
        borderRadius: BorderRadius.circular(10),
        boxShadow: [
          BoxShadow(
            color: theme.shadowColor.withOpacity(0.03),
            blurRadius: 1,
            offset: const Offset(0, 1),
          ),
        ],
      ),
      child: child,
    );
  }

  // 构建真实相册列表
  List<Widget> _buildRealAlbumsList() {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;
    final selectedAlbums = ref.watch(photoBackupProvider).selectedAlbums;

    return _albums.map((album) {
      final bool isSelected = selectedAlbums[album.id] ?? false;

      return Padding(
        padding: const EdgeInsets.only(bottom: 4.0),
        child: _buildCardItem(
          child: _buildRealAlbumTile(
            album: album,
            isSelected: isSelected,
            onChanged: (value) {
              ref
                  .read(photoBackupProvider.notifier)
                  .setAlbumSelection(album.id, value);
            },
          ),
        ),
      );
    }).toList();
  }

  Widget _buildMainSwitchTile({
    required String title,
    String? labelText,
    required bool value,
    required ValueChanged<bool> onChanged,
  }) {
    final theme = Theme.of(context);
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 10.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Expanded(
            child: Row(
              children: [
                Text(title, style: theme.textTheme.titleMedium),
                if (labelText != null) ...[
                  const SizedBox(width: 6),
                  Text(
                    labelText,
                    style: theme.textTheme.bodyMedium?.copyWith(
                      color: theme.textTheme.bodySmall?.color,
                    ),
                  ),
                ],
              ],
            ),
          ),
          Transform.scale(
            scale: 0.7,
            child: Switch(
              value: value,
              onChanged: onChanged,
              activeColor: theme.colorScheme.primary,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildVipSwitchTile({
    required String title,
    String? subtitle,
    required bool value,
    required ValueChanged<bool> onChanged,
  }) {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;

    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 10.0),
      child: Row(
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Row(
                children: [
                  Text(title, style: theme.textTheme.titleMedium),
                  const SizedBox(width: 8),
                  Container(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 6,
                      vertical: 2,
                    ),
                    decoration: BoxDecoration(
                      color: colorScheme.primary,
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: Text(
                      'SVIP',
                      style: theme.textTheme.labelSmall?.copyWith(
                        color: colorScheme.onPrimary,
                      ),
                    ),
                  ),
                ],
              ),
              if (subtitle != null)
                Text(subtitle, style: theme.textTheme.bodySmall),
            ],
          ),
          const Spacer(),
          Transform.scale(
            scale: 0.7,
            child: Switch(
              value: value,
              onChanged: onChanged,
              activeColor: colorScheme.primary,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSelectionTile({
    required String title,
    String? subtitle,
    required bool selected,
    required VoidCallback onTap,
  }) {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;

    return InkWell(
      onTap: onTap,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 10.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(title, style: theme.textTheme.titleMedium),
                if (subtitle != null)
                  Text(subtitle, style: theme.textTheme.bodySmall),
              ],
            ),
            const Spacer(),
            // 简化为简单的圆形选择指示器
            Transform.scale(
              scale: 0.7,
              child: Container(
                width: 22,
                height: 22,
                decoration: BoxDecoration(
                  color: selected ? colorScheme.primary : theme.disabledColor,
                  shape: BoxShape.circle,
                ),
                child:
                    selected
                        ? Icon(
                          Icons.check,
                          color: colorScheme.onPrimary,
                          size: 16,
                        )
                        : null,
              ),
            ),
            // 保持与开关一样的位置
            const SizedBox(width: 13),
          ],
        ),
      ),
    );
  }

  Widget _buildNavigationTile({
    required String title,
    required String label,
    required Color labelColor,
    required VoidCallback onTap,
  }) {
    return InkWell(
      onTap: onTap,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 10.0),
        child: Row(
          children: [
            Text(
              title,
              style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w400),
            ),
            const Spacer(),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
              decoration: BoxDecoration(
                color: labelColor.withOpacity(0.1),
                borderRadius: BorderRadius.circular(10),
              ),
              child: Text(
                label,
                style: TextStyle(color: labelColor, fontSize: 12),
              ),
            ),
            const SizedBox(width: 8),
            const Icon(Icons.chevron_right, color: Colors.grey, size: 18),
          ],
        ),
      ),
    );
  }

  // 构建真实相册项
  Widget _buildRealAlbumTile({
    required AssetPathEntity album,
    required bool isSelected,
    required ValueChanged<bool> onChanged,
  }) {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;
    final backupState = ref.read(photoBackupProvider);

    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 16.0),
      child: Row(
        children: [
          // 相册缩略图
          Container(
            width: 48,
            height: 48,
            decoration: BoxDecoration(
              color:
                  theme.brightness == Brightness.light
                      ? Colors.grey.shade200
                      : Colors.grey.shade800,
              borderRadius: BorderRadius.circular(4),
            ),
            child:
                _thumbnailCache[album.id] != null
                    ? ClipRRect(
                      borderRadius: BorderRadius.circular(4),
                      child: Image.memory(
                        _thumbnailCache[album.id]!,
                        fit: BoxFit.cover,
                      ),
                    )
                    : Icon(
                      _getAlbumIcon(album),
                      color: colorScheme.primary,
                      size: 28,
                    ),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(album.name, style: theme.textTheme.titleMedium),
                const SizedBox(height: 2),
                Builder(
                  builder: (context) {
                    final cachedCount = _albumAssetCountCache[album.id];
                    int count = 0;

                    if (cachedCount != null) {
                      if (backupState.autoBackupPhotos &&
                          backupState.autoBackupVideos) {
                        count =
                            (cachedCount[AssetType.image] ?? 0) +
                            (cachedCount[AssetType.video] ?? 0);
                      } else if (backupState.autoBackupPhotos) {
                        count = cachedCount[AssetType.image] ?? 0;
                      } else if (backupState.autoBackupVideos) {
                        count = cachedCount[AssetType.video] ?? 0;
                      }
                    }

                    String countText;
                    if (backupState.autoBackupPhotos &&
                        backupState.autoBackupVideos) {
                      countText = '共$count个项目';
                    } else if (backupState.autoBackupPhotos) {
                      countText = '共$count张照片';
                    } else if (backupState.autoBackupVideos) {
                      countText = '共$count个视频';
                    } else {
                      countText = '共$count个项目';
                    }

                    return Text(countText, style: theme.textTheme.bodySmall);
                  },
                ),
              ],
            ),
          ),
          Transform.scale(
            scale: 0.7,
            child: Switch(
              value: isSelected,
              onChanged: onChanged,
              activeColor: colorScheme.primary,
            ),
          ),
        ],
      ),
    );
  }

  // 获取相册图标
  IconData _getAlbumIcon(AssetPathEntity album) {
    final String name = album.name.toLowerCase();
    if (name.contains('camera') || name.contains('dcim')) {
      return Icons.camera_alt;
    } else if (name.contains('screenshot') || name.contains('截图')) {
      return Icons.screenshot;
    } else if (name.contains('wechat') || name.contains('微信')) {
      return Icons.chat;
    } else {
      return Icons.photo_library;
    }
  }

  // 构建加密备份提示
  Widget _buildEncryptionTip(ColorScheme colorScheme) {
    return Row(
      children: [
        SizedBox(
          width: 20,
          height: 20,
          child: Icon(
            Icons.shield_outlined,
            color: colorScheme.primary,
            size: 20,
          ),
        ),
        const SizedBox(width: 8),
        Expanded(
          child: Text(
            '咕噜酱正在努力备份相册内容',
            style: TextStyle(color: colorScheme.primary, fontSize: 14),
          ),
        ),
        TextButton(
          onPressed: () {
            Navigator.of(context).pushNamed(Routes.transferList);
          },
          style: TextButton.styleFrom(
            minimumSize: Size.zero,
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
            tapTargetSize: MaterialTapTargetSize.shrinkWrap,
          ),
          child: Text(
            '监督咕噜酱 >',
            style: TextStyle(color: colorScheme.primary, fontSize: 14),
          ),
        ),
      ],
    );
  }

  // 构建加载相册提示
  Widget _buildLoadingTip(ColorScheme colorScheme) {
    String loadingText;
    double progress = 0.0;

    if (_pendingAlbums.isNotEmpty && _allAlbumCache.isNotEmpty) {
      final int loaded = _albumAssetCountCache.length;
      final int total = _pendingAlbums.length + loaded;
      progress = loaded / total;
      loadingText = '相册加载中：已完成 $loaded/$total 个';
    } else if (_isLoading && _allAlbumCache.isEmpty) {
      loadingText = '正在加载相册列表...';
    } else {
      loadingText = '正在处理相册数据...';
    }

    return Row(
      children: [
        SizedBox(
          width: 20,
          height: 20,
          child: Center(
            child: SizedBox(
              width: 16,
              height: 16,
              child: CircularProgressIndicator(
                strokeWidth: 2,
                value: progress > 0 ? progress : null,
                valueColor: AlwaysStoppedAnimation<Color>(colorScheme.primary),
              ),
            ),
          ),
        ),
        const SizedBox(width: 8),
        Expanded(
          child: Text(
            loadingText,
            style: TextStyle(color: colorScheme.primary, fontSize: 14),
          ),
        ),
        // 添加空的按钮，保持与加密提示相同布局宽度
        const SizedBox(
          width: 76, // 与"监督咕噜酱 >"按钮宽度大致相同
          height: 28, // 与按钮高度一致
        ),
      ],
    );
  }

  // 修改相册选择标题部分
  Widget _buildAlbumSelectionTitle() {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;
    final isAllSelected = ref.watch(photoBackupProvider).isAllAlbumsSelected;

    return FadeTransition(
      opacity: _animationController,
      child: SizeTransition(
        sizeFactor: _animationController,
        axisAlignment: -1.0,
        child: Padding(
          padding: const EdgeInsets.only(left: 4, top: 10, bottom: 4, right: 4),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text('选择自动备份的相册', style: theme.textTheme.titleMedium),
              Row(
                children: [
                  // 添加刷新按钮
                  RotationTransition(
                    turns: Tween(
                      begin: 0.0,
                      end: 1.0,
                    ).animate(_refreshController),
                    child: IconButton(
                      onPressed: _isRefreshing ? null : _refreshAlbumsCache,
                      icon: Icon(
                        Icons.refresh,
                        color:
                            _isRefreshing
                                ? colorScheme.primary.withOpacity(0.6)
                                : colorScheme.primary,
                      ),
                      tooltip: _isRefreshing ? '刷新中...' : '刷新相册',
                      padding: const EdgeInsets.all(4),
                      constraints: const BoxConstraints(),
                      iconSize: 20,
                      splashRadius: 20,
                    ),
                  ),
                  const SizedBox(width: 8),
                  TextButton(
                    onPressed: () {
                      ref.read(photoBackupProvider.notifier).toggleAllAlbums();
                    },
                    style: TextButton.styleFrom(
                      padding: const EdgeInsets.symmetric(horizontal: 8),
                      minimumSize: Size.zero,
                      tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                      foregroundColor: colorScheme.primary,
                    ),
                    child: Text(
                      isAllSelected ? '取消全选' : '全选',
                      style: theme.textTheme.labelLarge?.copyWith(
                        color: colorScheme.primary,
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 手动刷新相册缓存和缩略图（添加防抖功能）
  Future<void> _refreshAlbumsCache() async {
    // 如果还在防抖冷却期或正在加载/刷新，不执行操作
    if (_debounceTimer?.isActive == true || _isLoadingBatch || _isRefreshing) {
      return;
    }

    // 设置刷新状态并启动动画
    setState(() {
      _isRefreshing = true;
    });

    // 循环运行刷新动画
    _refreshController.repeat();

    try {
      // 清除本地缓存
      setState(() {
        _isLoading = true;
        _allAlbumCache = [];
        _albumAssetCountCache = {};
        _thumbnailCache = {};
        _hasLoadedData = false;
        _pendingAlbums = [];
      });

      // 显示加载提示
      _tipSwitchController.forward();

      // 清理缩略图缓存目录
      await _cleanThumbnailCache();

      // 清除全局状态缓存
      await _clearGlobalCache();

      // 强制重新加载相册
      await _loadAlbums();
    } catch (e) {
      print('刷新失败: $e');
    } finally {
      // 无论成功失败，都重置刷新状态
      if (mounted) {
        setState(() {
          _isRefreshing = false;
        });
        // 停止动画
        _refreshController.reset();

        // 设置防抖计时器，3秒内不能再次点击
        _debounceTimer?.cancel();
        _debounceTimer = Timer(const Duration(seconds: 3), () {
          // 防抖期结束
        });
      }
    }
  }

  // 清理缩略图缓存目录
  Future<void> _cleanThumbnailCache() async {
    try {
      final appDir = await getApplicationDocumentsDirectory();
      final thumbnailDir = Directory('${appDir.path}/album_thumbnails');
      if (await thumbnailDir.exists()) {
        // 删除整个目录及其内容
        await thumbnailDir.delete(recursive: true);
        // 重新创建空目录
        await thumbnailDir.create();
      }
    } catch (e) {
      print('清理缩略图缓存失败: $e');
    }
  }

  // 清除全局状态缓存
  Future<void> _clearGlobalCache() async {
    try {
      final photoBackupNotifier = ref.read(photoBackupProvider.notifier);
      // 保留所有用户设置，只清除相册缓存数据
      photoBackupNotifier.clearAlbumCache();
      await photoBackupNotifier.saveState();
    } catch (e) {
      print('清除全局缓存失败: $e');
    }
  }

  // 添加显示并行备份数量选择对话框的方法
  void _showParallelBackupCountDialog() {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;
    final currentCount = ref.read(photoBackupProvider).parallelBackupCount;

    showModalBottomSheet(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (context) {
        return Container(
          padding: const EdgeInsets.only(top: 10, bottom: 20),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 底部滑块指示器
              Container(
                width: 40,
                height: 4,
                decoration: BoxDecoration(
                  color: Colors.grey.shade300,
                  borderRadius: BorderRadius.circular(2),
                ),
                margin: const EdgeInsets.only(bottom: 10),
              ),
              // 标题
              const Padding(
                padding: EdgeInsets.symmetric(vertical: 10),
                child: Text(
                  '选择并行备份的文件数',
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                ),
              ),
              // 选项
              _buildParallelCountOption(3, currentCount),
              _buildParallelCountOption(5, currentCount),
              _buildParallelCountOption(10, currentCount),
            ],
          ),
        );
      },
    );
  }

  // 构建并行数量选项
  Widget _buildParallelCountOption(int count, int currentCount) {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;

    return InkWell(
      onTap: () {
        ref.read(photoBackupProvider.notifier).setParallelBackupCount(count);
        Navigator.pop(context);
      },
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 20),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              '最高$count个文件',
              style: TextStyle(
                fontSize: 15,
                color:
                    currentCount == count ? colorScheme.primary : Colors.black,
              ),
            ),
            if (currentCount == count)
              Icon(Icons.check, color: colorScheme.primary, size: 20),
          ],
        ),
      ),
    );
  }

  // 创建相册信息对象
  AlbumInfo _createAlbumInfo(AssetPathEntity album) {
    final typeCount = _albumAssetCountCache[album.id];

    return AlbumInfo(
      id: album.id,
      name: album.name,
      imageCount: typeCount?[AssetType.image] ?? 0,
      videoCount: typeCount?[AssetType.video] ?? 0,
    );
  }
}
